<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\Models\Category;
use DB;

class CategoryController extends Controller
{
    /**
     * ***后台板块的遍历页面****
     * @$list 查询到所有的板块详情
     * return 绑定视图
     */
    public function index()
    {
        $category = new Category();

        $list = $category->categoryGet();
//        dd($list);
        return view('admin.category.category',['list'=>$list]);
    }

    /**
     **** ajax添加一后台板块***
     * @$data 取得添加板块名
     * @$path 找到父板块的path
     * @$tid  父板块的id
     * @$data['path] 重新组装新的路径
     * @$id 获取自增的id
     * return @$list  用自增的id找到添加板块信息并返回ajax
     */
    public function add(Request $request)
    {
        $category = new Category();
        $data = $request->except('_token');
        $category->store_id= session('storelist')['id'];
        $category->pic=$data['pic'] ;
        $category->name=$data['name'] ;
        $category-> status= 1;
        $category->pid = $data['pid'];
        $category->path = $data['path'];   //此情况说明是顶级分类
        if(empty($category->path)){
            //查询之前pid的表的path
            $li=$category->find($data['pid']);
            //path：父类的path拼接当前id
            $category->path = $li->path.$li->id.',';
        }
        $category->save();
        $id=$category->id;
        if($id>0){
            $list = $category->categoryFirst($id);
            return $list;
        }else{
            return null;
        }



    }
        //显示添加视图
    public function doadd()
    {
        return view('admin.category.test');
    }

    /**
     * **通过ajax删除板块***
     * @$id 要删除的板块id
     * return @$row 删除成功后返回的影响行数
     *
     */
    public function del(Request $request)
    {

        $category = new Category();
        $id = $request->input('id');
        $row = $category->categoryDestroy($id);
        if($row>0){
            return $row;
        }else{
            return null;
        }
    }
        /**
         *更改版块名
        * @param $request
         * @return $row;
        */
    public function edit(Request $request)
    {
        $category = new Category();

        $row = $category->categoryUpdate($request);

        if($row>0){
            return $row;
        }else{
            return null;
        }

    }

    /**
     *删除前查询是否有子版块
     * @param $request
     * @return $row;
     */
    public function query(Request $request)
    {
        $category = new Category();
        $id = $request->input('id');
        $list = $category->categoryQuery($id);

//        dd(empty($list));
        if($list->count() != 0){
            return json_encode(array("name"=>"亲,此版块下面子版块，不可以删除哦！"));
        }else{
            return json_encode(array("name"=>'亲，你确定要删除吗!'));
        }
    }


}

